//
//  ListenTestCatalogueViewController.m
//  xpkc
//
//  Created by wanmeizty on 14-10-16.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "ListenTestCatalogueViewController.h"

@interface ListenTestCatalogueViewController (){
    UIScrollView *scrollView;
    NSMutableArray *catalogueArray;
    NSMutableArray *colorRArray;
    NSMutableArray *colorGArray;
    NSMutableArray *colorBArray;
    NSMutableArray *btnArray;
    CGPoint startPoint;
    UIButton *tempBtn;
    CGRect tempFrame;
    CGFloat xx;//偏移距离
    CGFloat yy;
    int xP;//偏移单位
    int yP;
    int startIndex;//起始按钮数组位置
    int stopIndex;
    CGFloat buttonW;//按钮宽度
    CGFloat buttonH;
    int numLine;//每行个数
    CGFloat spaceSize;//间隔大小
}

@end

@implementation ListenTestCatalogueViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                 [UIColor colorWithRed:255/255.0f green:159/255.f blue:0/255.f alpha:1], NSForegroundColorAttributeName,
                                                 nil] forState:UIControlStateSelected];
        self.navigationItem.title = @"免费试听";
        self.tabBarItem.title = @"试听";
        self.tabBarItem.image = [UIImage imageNamed:@"listentest"];
        if (IsIOS7) {
            self.tabBarItem.selectedImage = [[UIImage imageNamed:@"listentest_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        }
    }
    return self;
}
/**
 *  创建视图
 */
-(void)creatView{
    if (isPad) {
        spaceSize = 40;
        numLine = 3;
    }else{
        spaceSize = 20;
        numLine = 2;
    }
    buttonW = (SCREEN_WIDTH-spaceSize*(numLine+1))/numLine;
    buttonH = buttonW;
    
    scrollView = [[UIScrollView alloc]init];
    scrollView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-self.tabBarController.tabBar.frame.size.height);
    
    scrollView.showsVerticalScrollIndicator = FALSE;
    scrollView.backgroundColor = BGColor;
    scrollView.userInteractionEnabled = YES;
    btnArray = [NSMutableArray array];
    [self.view addSubview:scrollView];
    //开始获取
    [self getLocalCatelogueInfo];
}
/**
 *  界面赋值
 */
-(void)setViewValue:(int)local{
    scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, (catalogueArray.count+1)/2*(buttonH+spaceSize)+spaceSize);
    [btnArray removeAllObjects];
    NSMutableIndexSet *indexset = [[NSMutableIndexSet alloc]init];
    for (int i = 0; i<catalogueArray.count; i++) {
        //
        NSDictionary *dic = [catalogueArray objectAtIndex:i];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//        int random=0;
//        random =arc4random()%7;
        
        if (local == 0) {
            //没有颜色属性，保存随机的颜色属性
            int c;
            c =  arc4random()%colorRArray.count;
            //保证不重复颜色
            while ([indexset containsIndex:c]) {
                c = arc4random()%catalogueArray.count;
            }
            [indexset addIndex:c];
            //FIXME:配色方案
            NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithDictionary:dic];
            [newDic setValue:[NSString stringWithFormat:@"%d",i] forKey:@"color"];
            
            button.backgroundColor = RGBCOLOR([[colorRArray objectAtIndex:i]intValue], [[colorGArray objectAtIndex:i]intValue], [[colorBArray objectAtIndex:i]intValue]);
            [catalogueArray setObject:newDic atIndexedSubscript:i];
        }else{
            int c = [[dic objectForKey:@"color"]intValue];
            button.backgroundColor = RGBCOLOR([[colorRArray objectAtIndex:c]intValue], [[colorGArray objectAtIndex:c]intValue], [[colorBArray objectAtIndex:c]intValue]);
        }
        button.frame = CGRectMake(i%numLine*(buttonW+spaceSize)+spaceSize, i/numLine*(buttonH+spaceSize)+spaceSize, buttonW, buttonH);
        [button setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 5)];
        if (isPad) {
            button.titleLabel.font = [UIFont boldSystemFontOfSize:20];
        }else{
            button.titleLabel.font = [UIFont boldSystemFontOfSize:16];
        }
        button.titleLabel.numberOfLines = 0;
        button.tag = [[dic objectForKey:@"id"]intValue];
        [button setTitle:[dic objectForKey:@"TypeNmae"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(catalogueButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(touch:)];
        [button addGestureRecognizer:longPress];
        [scrollView addSubview:button];
        [btnArray addObject:button];
    }
}
/**
 *  创建导航栏按钮
 */
-(void)creatNavItemView{
    UIBarButtonItem *manageBtn = [[UIBarButtonItem alloc]initWithTitle:@"更新" style:UIBarButtonItemStyleBordered target:self action:@selector(catalogueManager)];
    [manageBtn setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:GreenColor,NSForegroundColorAttributeName,[UIFont systemFontOfSize:16.0], NSFontAttributeName, nil] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = manageBtn;
}
/**
 *  获取目录信息
 */
-(void)getCatalogueInfo{
    NSString *timeString = [NSString stringWithFormat:@"%@", [GetTime getTime]];
    NSString *string1 = [NSString stringWithFormat:@"/OpenCourse/ColumnList/key/0b6f2f666ddfd0e56e4d566f12a0f353/time/%@", timeString];
    NSString *MD5string = [string1 md5];
    NSString *urlString = [NSString stringWithFormat:@"http://www.studypay.com/MAPI/index.php/OpenCourse/ColumnList/hash/%@/appid/1", MD5string];
    //POST请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:timeString,@"time", nil];
    [manager POST:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        /**
         *  判断发送请求的格式是否正确，不正确的话返回的参数是比较蛋疼的
         */
        if ([dic objectForKey:@"timerror"]) {
            //logdebug(@"faterror:退出登录");
            [UserMessage sharedUserMessage].isLogin = NO;
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请确保手机时间与北京时间相差五分钟以内" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alert show];
            return ;
        }
        catalogueArray = [NSMutableArray arrayWithArray:[dic objectForKey:@"info"]];
        [self setViewValue:0];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //
    }];
}
/**
 *  获取本地的目录信息
 */
-(void)getLocalCatelogueInfo{
    catalogueArray= [NSMutableArray arrayWithContentsOfFile:CATAGOLUE_PATH];
    if (catalogueArray.count!=0) {
        //
        //logdebug(@"本地已有");
        [self setViewValue:1];
    }else{
        //FIXME:请求网络的时候以后修改
        [self getCatalogueInfo];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (IsIOS7) {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    // Do any additional setup after loading the view.
    colorRArray = [[NSMutableArray alloc]initWithObjects:@"220",@"219",@"70",@"74",@"199",@"181",@"75",@"85",@"210",@"228",@"238",@"142",@"51",@"144",@"197",@"152",@"84",@"102",@"226",@"224",@"51",@"79",@"66", nil];
    colorGArray = [[NSMutableArray alloc]initWithObjects:@"180",@"72",@"139",@"185",@"162",@"70",@"196",@"220",@"80",@"107",@"149",@"201",@"127",@"158",@"123",@"109",@"222",@"129",@"112",@"178",@"127",@"210",@"28", nil];
    colorBArray = [[NSMutableArray alloc]initWithObjects:@"84",@"78",@"222",@"222",@"101",@"204",@"151",@"209",@"139",@"112",@"39",@"57",@"157",@"189",@"100",@"97",@"157",@"80",@"47",@"53",@"175",@"111",@"159", nil];
    
    [self creatView];
    [self creatNavItemView];
}
/**
 *  项目按钮点击
 *
 *  @param btn btn
 */
-(void)catalogueButtonClick:(UIButton *)btn{
//    logdebug(@"%d%@",btn.tag,btn.titleLabel.text);
//    //TODO:界面跳转
//    ListenTestViewController *listenTest = [[ListenTestViewController alloc]init];
//    listenTest.typeId = btn.tag;
//    listenTest.className = btn.titleLabel.text;
//    [listenTest setTitle:[NSString stringWithFormat:@"%@试听",btn.titleLabel.text]];
//    [self.navigationController pushViewController:listenTest animated:YES];
//    //自定义返回钮也能够左拉返回
//    if (IsIOS7) {
//        if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
//            self.navigationController.interactivePopGestureRecognizer.delegate = nil;
//        }
//    }
}
/**
 *  长按拖动手势
 *
 *  @param ges ges
 */
-(void)touch:(UIGestureRecognizer *)ges{
    if (ges.state == UIGestureRecognizerStateBegan) {
        //logdebug(@"长按开始");
        //记录初始数据好做坐标运算
        startPoint = [ges locationInView:scrollView];
        //logdebug(@"%f:%f",startPoint.x,startPoint.y);
        startIndex = ((int)startPoint.x/(int)(SCREEN_WIDTH/numLine)*1+(int)startPoint.y/(int)(buttonH+spaceSize)*numLine);
//        NSDictionary *dic =[catalogueArray objectAtIndex:startIndex];
        //logdebug(@"初始%d:%@",startIndex,[dic objectForKey:@"TypeNmae"]);
        tempBtn = [btnArray objectAtIndex:startIndex];
        [scrollView bringSubviewToFront:tempBtn];
        tempFrame = tempBtn.frame;
        tempBtn.layer.shadowColor = [UIColor blackColor].CGColor;
        tempBtn.layer.shadowOffset = CGSizeMake(10, 10);
        tempBtn.layer.shadowOpacity = 0.4;
        
    }
    xx = [ges locationInView:scrollView].x-startPoint.x;
    yy = [ges locationInView:scrollView].y-startPoint.y;
    //logdebug(@"位移%f:%f",xx,yy);
    tempBtn.frame = CGRectMake(tempFrame.origin.x+xx, tempFrame.origin.y+yy, tempFrame.size.width, tempFrame.size.height);
    if (xx>=0) {
        xP = (int)(xx+(buttonW+spaceSize)/2)/(buttonW+spaceSize);
    }else{
        xP = (int)(xx-(buttonW+spaceSize)/2)/(buttonW+spaceSize);
    }
    if (yy>=0) {
        yP = (int)(yy+(buttonH+spaceSize)/2)/(buttonH+spaceSize);
    }else{
        yP = (int)(yy-(buttonH+spaceSize)/2)/(buttonH+spaceSize);
    }
    //logdebug(@"位移单位%d",xP+numLine*yP);
    if (ges.state == UIGestureRecognizerStateEnded) {
        //logdebug(@"长按结束");
        tempBtn.layer.borderWidth = 0;
        tempBtn.layer.shadowOffset = CGSizeMake(0, 0);
        tempBtn.layer.shadowColor = [UIColor whiteColor].CGColor;
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.2];
        //位移范围判定
        if (tempFrame.origin.x+xP*(buttonW+spaceSize)<=0) {
            logdebug(@"太左");
            xP = xP+1;
        }
        if (tempFrame.origin.x+xP*(buttonW+spaceSize)+spaceSize/2>=SCREEN_WIDTH) {
            logdebug(@"太右");
            xP = xP-1;
        }
        if (tempFrame.origin.y+yP*(buttonH+spaceSize)<=0) {
            logdebug(@"太上");
            yP = yP+1;
        }
        if (tempFrame.origin.y+yP*(buttonH+spaceSize) >= (buttonH+spaceSize)*((catalogueArray.count+1)/numLine)+spaceSize) {
            //
            logdebug(@"太往下了");
//            yP = yP-1;
            yP = catalogueArray.count/numLine-1;
        }
        tempBtn.frame = CGRectMake(tempFrame.origin.x+xP*(buttonW+spaceSize), tempFrame.origin.y+yP*(buttonH+spaceSize), tempFrame.size.width, tempFrame.size.height);
        [UIView commitAnimations];
        stopIndex = startIndex+xP+yP*numLine;
        if (stopIndex >= catalogueArray.count) {
            //确保断行的位置正确
            stopIndex = catalogueArray.count-1;
            tempBtn.frame = CGRectMake((catalogueArray.count-1)%numLine*(buttonW+spaceSize)+spaceSize, (catalogueArray.count-1)/numLine*(buttonH+spaceSize)+spaceSize, buttonW, buttonH);
        }
        if (stopIndex<0) {
            stopIndex =0;
        }
        logdebug(@"结束单位%d",stopIndex);
        if (stopIndex>startIndex) {
            //往下拉
            UIButton *btn = [btnArray objectAtIndex:stopIndex];
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDuration:0.6];
            btn.frame = CGRectMake(startIndex%numLine*(buttonW+spaceSize)+spaceSize, startIndex/numLine*(buttonH+spaceSize)+spaceSize, buttonW, buttonH);
            [UIView commitAnimations];
            [btnArray exchangeObjectAtIndex:startIndex withObjectAtIndex:stopIndex];
            [catalogueArray exchangeObjectAtIndex:startIndex withObjectAtIndex:stopIndex];
        }else{
            for (int i = (startIndex<stopIndex?startIndex:stopIndex); i<(startIndex>stopIndex?startIndex:stopIndex); i++) {
                //
                logdebug(@"换位置%d",i);
                UIButton *btn = [btnArray objectAtIndex:i];
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:0.6];
                [UIView setAnimationDelay:(i-(startIndex<stopIndex?startIndex:stopIndex)+1)*0.2];
                btn.frame = CGRectMake((i+1)%numLine*(buttonW+spaceSize)+spaceSize, (i+1)/numLine*(buttonH+spaceSize)+spaceSize, buttonW, buttonH);
                [UIView commitAnimations];
            }
            [btnArray insertObject:tempBtn atIndex:stopIndex];
            [btnArray removeObjectAtIndex:startIndex+1];
            [catalogueArray insertObject:[catalogueArray objectAtIndex:startIndex] atIndex:stopIndex];
            [catalogueArray removeObjectAtIndex:startIndex+1];
        }
    }
}
-(void)viewWillDisappear:(BOOL)animated{
    logdebug(@"视图消失:保存目录信息");
    //TODO:保存排列好的标签顺序
    logdebug(@"保存完成:%d",
    [catalogueArray writeToFile:CATAGOLUE_PATH atomically:YES]);
    [catalogueArray writeToFile:CATAGOLUE_PATH atomically:YES];
//    logdebug(@"保存位置:%@",DOC_PATH);
}
/**
 *  目录管理
 */
-(void)catalogueManager{
    logdebug(@"目录管理");
    //TODO:1刷新列表2删除或者修改列表
    for (UIButton *btn in btnArray) {
        [btn removeFromSuperview];
    }
    [self getCatalogueInfo];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
